package com.zto.sch.advance.caffeine;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.RemovalListener;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @program: sch-diy-parent
 * @description:基于时间驱逐
 * @author: sch
 * @create: 2020-12-25 21:55
 **/
public class CaffeineDemoExpel3 {
    public static void main(String[] args) throws InterruptedException {
        // 基于时间驱逐
        Cache cache = Caffeine
                .newBuilder()
                .maximumSize(10)
                // 写入之后开始计时失效
                .expireAfterWrite(2000, TimeUnit.MILLISECONDS)
                // 访问之后开始计时失效
                .expireAfterAccess(2000, TimeUnit.MILLISECONDS)
                // 自定义线程池执行RemovalListener
                .executor(new ThreadPoolExecutor(8,
                        8,
                        20,
                        TimeUnit.SECONDS, new ArrayBlockingQueue<>(16)))
                .removalListener((RemovalListener) (k, v, removalCause) -> {
                    System.out.println("移除: key = " + k + "，v = " + v + "，cause = " + removalCause);
                })
                .build();

        cache.put("key", "hello world");
        cache.put("key2", "hello world2");
        System.out.println(cache.getIfPresent("key"));
        TimeUnit.SECONDS.sleep(1);
        System.out.println(cache.getIfPresent("key2"));
        TimeUnit.SECONDS.sleep(2);
        System.out.println(cache.getIfPresent("key"));


    }
}
